package com.lisp.springframework.web.controller;

import javax.validation.Valid;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;


@Controller
public class Json2ObjectController {

    @CrossOrigin(origins = "https://www.baidu.com")
    @RequestMapping("/testJsonModel")
    @ResponseBody
    public People testJsonModel(@RequestBody @Valid People people) {
        /* 打开www.baidu.com, 在开发者工具console用下面的脚本测试
            $.ajax({
               url:"http://localhost:8080/springframework/testJsonModel",
               type:'POST',
               contentType: 'application/json',
               data:'{"name":"lisp", "age": 3}',
               success:function (data) {
                   console.log(data);
               }
            }) */
        return people;
    }
    
    public static class People {
        
        @NotNull(message = "姓名不能为空")
        @Size(max = 50, message = "姓名不能超过50个字符")
        private String name;
        
        @NotNull(message = "年龄不能为空")
        @Max(value = 120, message = "年龄必须小于等于120")
        @Min(value = 0, message = "年龄必须大于等于0")
        private Integer age;

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public Integer getAge() {
            return age;
        }

        public void setAge(Integer age) {
            this.age = age;
        }

        @Override
        public String toString() {
            return "People [name=" + name + ", age=" + age + "]";
        }
    }
}
